package com.example.lightsabercontroller

import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.content.Intent
import android.util.Log
import android.widget.Toast
import java.io.IOException
import java.util.*

class BluetoothController {

    private val mBtAdapter = BluetoothAdapter.getDefaultAdapter()
    private lateinit var btSocket: BluetoothSocket

    /**
     * 判断是否支持蓝牙设备
     * @return true 支持 false不支持
     */
    fun isSupportBluetooth() = mBtAdapter != null

    fun getBluetoothStatus(): Boolean = mBtAdapter?.isEnabled ?: false

    fun turnOnBluetooth(activity: Activity, requestCode: Int) {
        val mIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
        /**
         * 申请打开蓝牙，此方法具有回调函数，具体回调函数需要重写Activity的方法
         */
        activity.startActivityForResult(mIntent, requestCode)
        mBtAdapter.enable()
//        mBtAdapter.bondedDevices
    }

    /**
     * 关闭蓝牙
     */
    fun turnOffBluetooth() {
        mBtAdapter.disable()
    }

    fun getBondedDevices(): MutableSet<BluetoothDevice> = mBtAdapter.bondedDevices

    private fun getUUID(): UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")

    fun connectToLightSaber(saberName: String): Boolean {
        var rc = false
        val saber = mBtAdapter.getRemoteDevice(saberName)
        mBtAdapter.cancelDiscovery()
        try {
            btSocket = saber.createRfcommSocketToServiceRecord(getUUID())
            btSocket.connect()
            Log.d("蓝牙", "蓝牙连接成功")
            rc = btSocket.isConnected
//            Toast.makeText(this, "连接建立", Toast.LENGTH_SHORT)
        }
        catch (e: IOException) {
            try {
                btSocket.close()
            }
            catch (e2: IOException) {
                Log.d("蓝牙", "蓝牙断开连接失败")
            }
            Log.d("蓝牙", "创建连接失败")
        }
        return rc
    }

    fun btSendData(data: String) {
        if (btSocket.isConnected) {
            val outStream = btSocket.outputStream
            try {
                outStream.write(data.toByteArray())
            }
            catch (e: IOException) {
                Log.d("蓝牙", "发送数据失败")
            }
        }
    }
}

